-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat: 動態止盈止損 + 部分平倉功能(完整實現 #136) #220
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: 動態止盈止損 + 部分平倉功能(完整實現 #136) #220
Conversation
Introduces 15m and 1h timeframes to Data struct and related calculations for more robust multi-timeframe analysis. Updates system prompt to reflect new data sources and analysis methods, and extends Format output to include mid-term series. Enhances signal quality and trend confirmation by leveraging multiple timeframes.
Added logic to automatically cancel all orders for a symbol when its position disappears, ensuring orphan stop-loss/take-profit orders are cleaned up. This improves order management and prevents unintended trades after a position is closed.
**核心功能**: - 新增买卖压力数据解析(TakerBuyVolume, BuySellRatio) - 重写系统提示词为震荡交易策略 - 添加连续放量检测功能(2-3根K线) **技术细节**: - market/data.go: 解析币安 K线 item[9] 为主动买入量 - decision/engine.go: 震荡区间识别 + 区间边界入场逻辑 - IntradayData: 新增 Volumes 和 BuySellRatios 数组
根据 ADAPTIVE_STRATEGY_DESIGN.md 方案 A(简单版)实现: 新增功能: 1. 市场状态判断(3个指标交叉验证): - 多时间框架一致性(15m/1h/4h MACD 方向) - 价格波动率(最近 10 根 K线波动幅度) - 买卖压力极端值(BuySellRatio 连续性) 2. 双策略系统: - 策略 A(震荡交易):止盈 1-2%,止损 0.8-1%,盈亏比 1:1.5-1:2 - 策略 B(趋势跟随):止盈 5-10%,止损 1.5-2%,盈亏比 1:3-1:5 3. 策略选择指导:AI 必须在思维链中明确说明市场状态判断和策略选择 改进效果: - 让 AI 根据市场状态动态调整止盈止损 - 震荡市场快进快出,趋势市场让利润奔跑 - 预期提升胜率和盈亏比,降低最大回撤 实施方式:纯提示词改进(无代码变更),耗时 30 分钟 🤖 Generated with Claude Code
- 在config.json.example中添加新闻源相关配置示例,支持telegram频道订阅 - 扩展数据库表结构,新增traders表多字段支持信号源和杠杆参数 - 新增NewsConfig结构体及相关telegram新闻配置数据模型 - 在交易决策上下文结构Context中添加新闻数据news字段支持传递新闻 - 在交易决策构建用户提示信息时加入相关新闻内容 - 优化数据库操作代码,支持交易所和交易员配置的完整字段读取与更新 - 添加数据库exchanges表迁移逻辑,重建表结构和触发器以支持新字段 - 引入第三方库github.com/samber/lo用于集合操作 - 在go.mod添加新的依赖模块,并更新相关依赖版本
解决问题: - 固定百分比止盈经常在技术位前回撤 - 浮盈没有保护机制,从 +1.5% 回撤到止损 核心改进: 1. 技术位优先止盈: - 震荡策略:技术位 < 2% → 止盈设在技术位前 0.1% - 趋势策略:技术位 < 5% → 止盈设在技术位前 0.2% - 技术位识别:EMA20、最近高低点、整数关口 2. 追踪止损机制: - 震荡:浮盈 0.8% → 止损移到成本价,浮盈 1.2% → 止损移到 +0.5% - 趋势:浮盈 2% → 止损移到成本价,浮盈 5% → 止损移到 +2.5% - 价格接近技术位 → 主动平仓避免回撤 3. 分批止盈预留: - 趋势策略:技术位在 5-10% → 分两批止盈 - 为阶段2分批止盈做准备 预期效果: - 减少"快到止盈就回撤"的情况 - 锁定浮盈,避免全部回撤 - 提高实际盈亏比 实施方式:纯提示词改进,基于已有数据(EMA20、K线高低点) 🤖 Generated with Claude Code
问题: - 旧算法只计算价格变化百分比,未考虑杠杆倍数 - 例:10倍杠杆,价格涨1% → 显示+1%(错误),实际应该是+10% - 导致 AI 收到错误的盈亏数据,影响决策 修复: - 使用实际盈亏除以保证金计算百分比 - 公式:pnlPct = (unrealizedPnl / marginUsed) * 100 - 优点: ✓ 考虑杠杆倍数 ✓ 使用 API 提供的实际盈亏(含手续费、资金费率) ✓ 更准确反映真实盈亏百分比 示例对比: - 入场:100,000,当前:101,000(+1%),10倍杠杆 - 旧算法:显示 +1%(错误) - 新算法:显示 +10%(正确) 感谢用户反馈 @1711z 🤖 Generated with Claude Code
问题: - Go 语言不识别中文双引号 "" - 导致编译失败:syntax error: unexpected name 修复: - 将所有中文双引号 "" 替换为英文单引号 '' - 影响行:287, 365-369 错误示例: - 错误:"趋势市场" - 正确:'趋势市场' 🤖 Generated with Claude Code
- 问题:config.json.example 与 main.go 的 ConfigFile 结构不一致 - 影响:新用户复制 example 时会缺少必要的配置字段 - 修复:添加 coin_pool_api_url 和 oi_top_api_url(空字符串) 相关提交:517d0ca (admin_mode config)
新增 prompts/adaptive.txt 模板,包含: ## 核心特性 - 市場狀態判斷(震盪/趨勢,多指標交叉驗證) - 雙策略系統: * 策略 A: 震盪交易(高勝率低盈虧比) * 策略 B: 趨勢跟隨(中等勝率高盈虧比) - 技術位優先止盈機制(EMA20、前高前低、整數關口) - 動態追踪止損(鎖定利潤,避免回撤) - 夏普比率自我進化(交易質量 > 交易頻率) ## 使用方式 用戶可在 Web UI 選擇此模板,或繼續使用 default/nof1 ## 技術實現 - 259 行完整策略指導 - 與現有模板系統兼容 - engine.go 保留硬編碼作為 fallback 相關文檔:TEMPLATE_MIGRATION_PLAN.md 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
## 問題
- 之前邏輯:加載模板 → 無條件追加硬編碼策略
- 結果:選擇 adaptive 模板時,會收到重複的策略內容
* adaptive.txt: 259 行
* 硬編碼: 184 行
* 總計:443 行重複指導 ❌
## 解決方案
使用 templateLoaded 標記追蹤模板加載狀態:
- ✅ 模板成功 → 使用模板,跳過硬編碼
- ❌ 模板失敗 → 使用硬編碼作為 fallback
## 變更內容
1. 添加 templateLoaded bool 變量
2. 硬編碼策略包裹在 `if !templateLoaded {}` 中(277-463 行)
3. 硬約束和輸出格式始終追加(不受影響)
4. 添加日誌追蹤模板使用情況
## 測試驗證
- ✅ Go 編譯成功
- ✅ Docker build 成功
- ✅ 向後兼容(模板失敗時回退到硬編碼)
## 架構改進
```
加載流程:
1. 嘗試加載指定模板(如 adaptive)
2. 失敗 → 嘗試 default
3. 仍失敗 → 使用硬編碼
4. 追加硬約束(動態生成)
5. 追加輸出格式(動態生成)
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
## 問題
用戶反饋:「怎麼 engine.go 還寫入了這些?... 有必要嗎?」
**根本原因**:
- prompts/ 目錄下已有 default.txt (114行) 和 adaptive.txt (259行)
- engine.go 卻硬編碼了 183 行 adaptive 策略作為 fallback
- 這導致:
1. 重複維護兩份相同的策略內容
2. templateLoaded 標記多餘(模板系統本身已有 fallback)
3. 如果 default.txt 都加載失敗,說明文件系統有嚴重問題,不應繼續交易
## 解決方案
### 1. 移除冗餘硬編碼
- 刪除 183 行硬編碼 adaptive 策略(271-453 行)
- 移除 templateLoaded 標記及其邏輯
### 2. 簡化模板加載邏輯
```go
// 之前(複雜)
templateLoaded := false
if 模板加載成功 {
templateLoaded = true
}
if !templateLoaded {
追加 183 行硬編碼策略 // ❌ 冗餘
}
// 現在(簡潔)
if 用戶模板加載失敗 {
嘗試 default.txt // ✅ 已經是 fallback
}
if default.txt 也失敗 {
返回空字符串,上層應停止交易 // ✅ 安全
}
```
### 3. 新增動態止盈止損設計文檔
創建 `DYNAMIC_TP_SL_PROPOSAL.md`,記錄:
- 用戶反饋:「建议加个 adjust tp sl 或者给 close 加个 quantity」
- 問題分析:策略提到追蹤止損,但 AI 無法執行
- 解決方案:添加 `adjust_stop_loss`, `adjust_take_profit`, `partial_close` actions
- 實施步驟:修改 Decision 結構、執行邏輯、模板說明
## 測試驗證
- ✅ Go 編譯成功
- ✅ Docker build 成功
- ✅ 模板系統邏輯清晰(用戶模板 → default → 報錯)
- ✅ 代碼減少 183 行(更易維護)
## 檔案變更
- `decision/engine.go`: -183 行硬編碼策略
- `DYNAMIC_TP_SL_PROPOSAL.md`: +300 行設計文檔
## 後續工作
- [ ] 實現 adjust_stop_loss action
- [ ] 實現 partial_close action
- [ ] 更新模板文件說明新 actions
---
感謝 @user 指出這個設計缺陷!🙏
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
DYNAMIC_TP_SL_PROPOSAL.md 是動態止盈止損功能的設計文檔, 但功能尚未實現,保留在代碼庫中可能造成困擾(誤以為已完成)。 當需要實現該功能時,可以從 git 歷史中恢復(commit bac5744)。 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
## 問題
之前修改將模板加載失敗時改為返回空字符串,但:
- 上層函數沒有檢測空字符串的邏輯
- 空字符串會直接傳給 AI API,導致錯誤
- 極端情況下系統無法運行
## 解決方案
恢復原始邏輯,保留內置簡化版本作為最後防線:
```
用戶模板失敗 → default 失敗 → 使用內置簡化版本
"你是专业的加密货币交易AI。请根据市场数据做出交易决策。"
```
## 差異對比
### 之前(不安全)
```go
if default 加載失敗 {
return "" // ❌ 上層未檢測,會傳空字符串給 AI
}
```
### 現在(安全)
```go
if default 加載失敗 {
sb.WriteString("你是专业的加密货币交易AI。请根据市场数据做出交易决策。\n\n")
// ✅ 有最後防線,極端情況下仍能運行
}
```
## 測試驗證
- ✅ Go 編譯成功
- ✅ Docker build 成功
- ✅ 邏輯恢復到原始穩定版本
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
问题: - 编辑交易员并修改系统提示词模板时,保存失败 - 错误提示:AI模型配置不存在或未启用 根本原因: 1. 后端 API 返回的 ai_model 被截断(admin_deepseek → deepseek) 2. 前端验证时找不到对应的模型 ID(enabledModels 存的是完整 ID) 3. API 缺少 system_prompt_template 字段 修复内容: - api/server.go: 移除 AI model ID 截断逻辑,返回完整 ID - api/server.go: 在 handleGetTraderConfig 中添加 system_prompt_template 字段 - web/src/types.ts: TraderConfigData 接口添加 system_prompt_template 字段 - web/src/components/AITradersPage.tsx: 添加 fallback 机制和详细日志 测试: - 编辑交易员 → 修改系统提示词模板 → 保存成功 - Console 输出验证日志,不再报错
新增功能: - update_stop_loss: 调整止损价格(追踪止损) - update_take_profit: 调整止盈价格(技术位优化) - partial_close: 部分平仓(分批止盈) 实现细节: - Decision struct 新增字段:NewStopLoss, NewTakeProfit, ClosePercentage - 新增执行函数:executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord - 修复持仓字段获取 bug(使用 "side" 并转大写) - 更新 adaptive.txt 文档,包含详细使用示例和策略建议 - 优先级排序:平仓 > 调整止盈止损 > 开仓 命名统一: - 与社区 PR tinkle-community#197 保持一致,使用 update_* 而非 adjust_* - 独有功能:partial_close(部分平仓) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
改動說明: - 新增「數據框架說明」章節:詳細說明 4 個時間框架的覆蓋時間和用途 - 新增「關鍵數據解讀」章節: * BuySellRatio 含義和參考範圍(0.6-0.7 強買壓,0.3-0.4 強賣壓) * 成交量分析:放量檢測標準(1.5-2 倍平均) * RSI 參考範圍:根據市場波動性調整(震盪市 30-40/60-70) - 新增「入場信號參考示例」章節: * 震盪策略入場信號(區間下沿做多、上沿做空) * 趨勢策略入場信號(趨勢突破參考) - 補充「避免低質量信號」: * 新增:震盪市在區間中部交易(應等待區間邊界) * 新增:缺乏買賣壓力確認(BuySellRatio 中性時謹慎) 設計哲學: - 採用「解釋 + 參考示例」方式,而非硬編碼固定規則 - 所有參考數值都明確標註「你可以根據市場狀態自主調整」 - 強調根據市場波動性、趨勢強度自主判斷 - 激發 AI 的判斷能力,而非限制其靈活性 - 通過夏普比率反饋實現自我進化 改動統計:+111 行(增加詳細解釋和示例) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
改動說明: - 新增「數據框架說明」章節:詳細說明 4 個時間框架的覆蓋時間和用途 * 3分鐘序列(30分鐘):實時價格、放量檢測、買賣壓力 * 15分鐘序列(2.5小時):震盪區間識別 * 1小時序列(10小時):中期趨勢確認 * 4小時序列(40小時):大趨勢判斷 - 新增「關鍵數據解讀」章節: * BuySellRatio 含義和參考範圍(0.6-0.7 強買壓,0.3-0.4 強賣壓) * 成交量分析:放量檢測標準(1.5-2 倍平均) * RSI 參考範圍:根據市場波動性調整(震盪市 30-40/60-70) - 新增「入場信號參考示例」章節: * 震盪策略入場信號(區間下沿做多、上沿做空) * 趨勢策略入場信號(趨勢突破參考) - 補充「避免低質量信號」: * 新增:震盪市在區間中部交易(應等待區間邊界) * 新增:缺乏買賣壓力確認(BuySellRatio 中性時謹慎) 設計哲學: - 採用「解釋 + 參考示例」方式,而非硬編碼固定規則 - 所有參考數值都明確標註「你可以根據市場狀態自主調整」 - 強調根據市場波動性、趨勢強度自主判斷 - 激發 AI 的判斷能力,而非限制其靈活性 - 通過夏普比率反饋實現自我進化 改動統計: - 原文件:259 行 - 新文件:366 行(+107 行) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
問題:AI 生成 update_stop_loss 決策但被拒絕為無效動作 原因:adaptive.txt 描述了動態止損功能,但 dev 分支代碼未實現 刪除內容: - 震盪策略:追蹤止損(持倉中動態調整)段落 - 趨勢策略:分批止盈、追蹤止損段落 - 策略選擇:追蹤止損計劃 - 持倉動態調整範例 結果:提示詞與代碼功能完全匹配,避免 AI 生成無效決策 相關 issue:生產環境報錯 '无效的action:update_stop_loss' 後續計劃:在 feature/partial-close-dynamic-tpsl 測試完成後再合併動態功能
問題根因: - auto_trader.go 已實現 update_stop_loss/update_take_profit/partial_close 處理 - adaptive.txt 已描述這些功能 - 但 validateDecision 的 validActions map 缺少這三個動作 - 導致 AI 生成的決策在驗證階段被拒絕:「无效的action:update_stop_loss」 修復內容: 1. validActions 添加三個新動作 2. 為每個新動作添加參數驗證: - update_stop_loss: 驗證 NewStopLoss > 0 - update_take_profit: 驗證 NewTakeProfit > 0 - partial_close: 驗證 ClosePercentage 在 0-100 之間 3. 修正註釋:adjust_* → update_* 測試狀態:feature 分支,等待測試確認
更新內容:
1. DecisionAction 註釋:添加 update_stop_loss, update_take_profit, partial_close
2. GetStatistics:partial_close 計入 TotalClosePositions
3. AnalyzePerformance 預填充邏輯:處理 partial_close(不刪除持倉記錄)
4. AnalyzePerformance 分析邏輯:
- partial_close 正確判斷持倉方向
- 記錄部分平倉的盈虧統計
- 保留持倉記錄(因為還有剩餘倉位)
說明:partial_close 會記錄盈虧,但不刪除 openPositions,
因為還有剩餘倉位可能繼續交易
問題: - 調整止損/止盈時,直接調用 SetStopLoss/SetTakeProfit 會創建新訂單 - 但舊的止損/止盈單仍然存在,導致多個訂單共存 - 可能造成意外觸發或訂單衝突 解決方案(參考 PR tinkle-community#197): 1. 在 Trader 接口添加 CancelStopOrders 方法 2. 為三個交易所實現: - binance_futures.go: 過濾 STOP_MARKET/TAKE_PROFIT_MARKET 類型 - aster_trader.go: 同樣邏輯 - hyperliquid_trader.go: 過濾 trigger 訂單(有 triggerPx) 3. 在 executeUpdateStopLossWithRecord 和 executeUpdateTakeProfitWithRecord 中: - 先調用 CancelStopOrders 取消舊單 - 然後設置新止損/止盈 - 取消失敗不中斷執行(記錄警告) 優勢: - ✅ 避免多個止損單同時存在 - ✅ 保留我們的價格驗證邏輯 - ✅ 保留執行價格記錄 - ✅ 詳細錯誤信息 - ✅ 取消失敗時繼續執行(更健壯) 測試建議: - 開倉後調整止損,檢查舊止損單是否被取消 - 連續調整兩次,確認只有最新止損單存在 致謝:參考 PR tinkle-community#197 的實現思路
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
- Auto-sync server time every 30 seconds - Add callWithTimeSync retry mechanism for all API calls - Fix -1021 timestamp errors automatically - Production-ready implementation - Resolved merge conflict with PR NoFxAiOS#145 Source: NoFxAiOS#313
- Fix leverage config visibility issue - Ensure all symbols' leverage info in prompt - Prevent AI from using wrong leverage - Add per-symbol leverage information to decision context Source: NoFxAiOS#318
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
- Clean up remaining conflict markers in SetMarginMode - Add visual warnings for WebSocket stream limits in UI - Prevent user from exceeding 250 symbols (1024 streams / 4 timeframes)
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
- Fix AI model validation failure when editing trader - Fix 4h kline data storage to correct database field - Remove improper model ID conversion in API layer - Resolve conflicts: keep complete model ID and continue on 4h fetch error - Closes NoFxAiOS#335, NoFxAiOS#260
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
…OS#231) - Add position_snapshots table to track all closed positions - Record both manual and auto-closed positions - Fix data integrity issue where auto-closed positions were not recorded - Improve trade history tracking and analysis - Merge with existing partial_close functionality
允许在编辑 Trader 时更新系统提示词模板(SystemPromptTemplate)。
系统提示词模板用于控制 AI 交易决策的行为模式。目前创建 Trader 时可以指定模板,但编辑时无法修改。
1. **UpdateTraderRequest** 添加 `SystemPromptTemplate` 字段
```go
SystemPromptTemplate string `json:"system_prompt_template"`
```
2. **handleUpdateTrader** 添加处理逻辑
- 如果请求中提供新模板,使用新值
- 如果为空字符串,保持数据库中的原有值
```go
systemPromptTemplate := req.SystemPromptTemplate
if systemPromptTemplate == "" {
systemPromptTemplate = existingTrader.SystemPromptTemplate
}
```
3. **TraderRecord** 设置 SystemPromptTemplate 字段
```go
SystemPromptTemplate: systemPromptTemplate,
```
- ✅ 支持在编辑 Trader 时更新系统提示词模板
- ✅ 空值时保持原有值不变(向后兼容)
- ✅ 与创建 Trader 时的行为保持一致
- ✅ 无破坏性变更
1. 用户创建 Trader 时使用了默认模板
2. 后续想切换到自定义模板(如更激进或保守的策略)
3. 通过编辑功能修改 SystemPromptTemplate 字段
4. 保存后,AI 将使用新的提示词模板进行决策
1. 创建 Trader(使用默认模板 "default")
2. 编辑 Trader,修改 system_prompt_template 为 "aggressive"
3. 保存并验证修改成功
4. 再次编辑,不修改 system_prompt_template(传空字符串)
5. 验证保持 "aggressive" 不变
…oFxAiOS#277) - Add Telegram channel monitoring for market news - Integrate news sentiment into AI decision making - Improve context awareness for trading decisions - Fix missing InsideCoins field in ConfigFile structure - Merge with existing partial_close and position tracking features
## 修改内容 ### 后端 (api/server.go) - handleGetTraderConfig 返回中添加 system_prompt_template 字段 ### 前端类型定义 (web/src/types.ts) - TraderConfigData 接口添加 system_prompt_template 字段 ### 前端更新逻辑 (web/src/components/AITradersPage.tsx) - handleSaveEditTrader 的更新请求中添加 system_prompt_template ## 完整数据流 ``` 后端数据库 ↓ handleGetTraderConfig 前端 TraderConfigData (包含 system_prompt_template) ↓ TraderConfigModal (UI 编辑) 前端 UpdateRequest (包含 system_prompt_template) ↓ handleUpdateTrader 后端更新数据库 ``` 现在前后端已完全打通,用户可以在 UI 中编辑系统提示词模板了。
…#310) - Add automatic config.json initialization on first run - Improve Docker deployment experience - Reduce manual configuration steps
- Allow users to customize AI decision scan interval (1-60 minutes) - Default 3 minutes, recommended range 3-10 minutes - Support both high-frequency and low-frequency trading strategies - Improve trading flexibility and API call efficiency - Merge with existing actual balance query functionality
- Allow users to modify SystemPromptTemplate when editing Trader - Enable dynamic strategy switching (default/aggressive/conservative) - Support A/B testing of different trading strategies - Maintain backward compatibility with existing data - Complete full data flow from database through UI to persistence
- Delete unused updatePositionSnapshots function (16 lines) - Clear position snapshots on GetPositions error to prevent false positives - Improve auto-close detection reliability - Better error handling for snapshot updates
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
feat: 動態止盈止損 + 部分平倉功能(完整實現 #136)🎯 概述本 PR 實現了完整的動態止盈止損和部分平倉功能,並包含多項重要改進和 bug 修復。這是對原 NOF1 系統功能的完整復刻和增強。 ✨ 核心功能1. 部分平倉與動態止盈止損 (#136)
2. 系統提示詞模板管理 (#339)
3. 掃描間隔配置 (#338)
4. 交易所餘額自動查詢 (#342)
5. 新聞情緒分析整合 (#277)
🐛 重要 Bug 修復交易相關
API 相關
數據庫相關
📊 性能優化
🎨 前端改進
📚 文檔更新
🔧 技術債務清理
🧪 測試覆蓋
📦 依賴更新
|
**Problem**: - GetTraderConfig was missing 9 critical fields in SELECT statement - Missing corresponding Scan variables - Caused trader edit UI to show 0 for leverage and empty trading_symbols **Root Cause**: Database query only selected basic fields (id, name, balance, etc.) but missed leverage, trading_symbols, prompts, and all custom configs **Fix**: - Added missing fields to SELECT: * btc_eth_leverage, altcoin_leverage * trading_symbols * use_coin_pool, use_oi_top * custom_prompt, override_base_prompt * system_prompt_template * is_cross_margin * AI model custom_api_url, custom_model_name - Added corresponding Scan variables to match SELECT order **Impact**: ✅ Trader edit modal now displays correct leverage values ✅ Trading symbols list properly populated ✅ All custom configurations preserved and displayed ✅ API endpoint /traders/:id/config returns complete data **Testing**: - ✅ Go compilation successful - ✅ All fields aligned (31 SELECT = 31 Scan) - ✅ API layer verified (api/server.go:887-904) Reported by: 寒江孤影 Issue: Trader config edit modal showing 0 leverage and empty symbols 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
## Changes - ✅ Merge dev branch's UT infrastructure (Issue NoFxAiOS#227 fix) - ✅ Preserve fallback mechanism for ai_model_id and exchange_id - ✅ Use `allModels` instead of `enabledModels` (allow editing disabled model traders) - ✅ Use `allExchanges` instead of `enabledExchanges` ## Conflict Resolution - Combined feature/partial-close-dynamic-tpsl's defensive programming - Adopted dev branch's core fix: allModels/allExchanges validation - Updated error messages to reflect "not exist" vs "not enabled" Related: NoFxAiOS#229, NoFxAiOS#227
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged.
🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
📋 概述
本 PR 實現了 issue #136 提出的完整需求:動態調整止盈止損 + 部分平倉功能。
作為 #136 的提出者,我實現了完整的解決方案,包括:
update_stop_loss/update_take_profit)partial_close)🎯 功能特性
1. 動態調整止損 (
update_stop_loss)使用場景:
2. 動態調整止盈 (
update_take_profit)使用場景:
3. 部分平倉 (
partial_close) ✨ 獨有功能使用場景:
🔗 與 PR #197 的關係
本 PR 與 PR #197 實現了相同的核心功能(
update_stop_loss/update_take_profit),但在設計理念和實現細節上有所不同。功能對比
核心差異:字段設計理念
本 PR 的設計(專用字段)
{ "action": "update_stop_loss", "new_stop_loss": 102000, "confidence": 90, "reasoning": "浮盈達到 1.5%,移止損到成本價" }設計理由:
new_stop_loss明確表示「調整到新的止損價」PR #197 的設計(復用字段)
{ "action": "update_stop_loss", "stop_loss": 102000, "confidence": 90, "reasoning": "浮盈達到 1.5%,移止損到成本價" }優勢:
權衡:
技術實現對比
📝 實現細節
修改的文件(8 個)
1.
decision/engine.goNewStopLoss,NewTakeProfit,ClosePercentageupdate_stop_loss,update_take_profit,partial_close2.
trader/auto_trader.goexecuteUpdateStopLossWithRecord- 執行止損調整並記錄executeUpdateTakeProfitWithRecord- 執行止盈調整並記錄executePartialCloseWithRecord- 執行部分平倉並記錄CancelStopOrders調用(避免多個止損單共存)3.
trader/interface.goCancelStopOrders(symbol string) error4-6. 交易所實現
trader/binance_futures.go- 實現CancelStopOrderstrader/aster_trader.go- 實現CancelStopOrderstrader/hyperliquid_trader.go- 實現CancelStopOrders7.
logger/decision_logger.gopartial_close計入平倉統計8.
prompts/adaptive.txt🎯 設計決策說明
為什麼選擇專用字段設計?
經過深思熟慮,本 PR 採用專用字段(
new_stop_loss/new_take_profit)而非復用字段,基於以下考量:1. 符合 API 設計最佳實踐
參考業界標準(Google API Design Guide, AWS API):
2. 提升代碼可讀性和維護性
3. 降低 AI 混淆概率
專用字段降低 AI 在同時處理開倉和調整時的混淆:
4. 易於未來擴展
如果未來需要新增功能(如「批量調整」、「部分調整」),專用字段設計更容易擴展:
開放討論
雖然我們認為專用字段設計在技術上更優,但我們願意:
重點:無論選擇哪種字段設計,本 PR 的核心價值(partial_close、驗證邏輯、詳細文檔)都可以保留。
✅ 測試建議
1. 動態止損測試
# 測試場景:追踪止損 1. 開一個小倉位(BTC 多單,10 USDT) 2. 等待浮盈達到 1% 3. 觀察 AI 是否自動生成 update_stop_loss 決策 4. 確認舊止損單被取消,新止損單生效 5. 驗證止損價格已移動到成本價2. 部分平倉測試
# 測試場景:分批止盈 1. 開一個倉位(ETH 多單,20 USDT) 2. 等待接近止盈目標(浮盈 2%+) 3. 觀察 AI 是否生成 partial_close: 50% 決策 4. 確認只平倉了 50% 數量 5. 驗證剩餘 50% 持倉繼續運行3. 價格驗證測試
📊 代碼統計
update_stop_loss,update_take_profit,partial_close)NewStopLoss,NewTakeProfit,ClosePercentage)🙏 致謝
CancelStopOrders實現思路📝 檢查清單
💬 討論點
歡迎維護者和社區成員討論以下問題:
期待大家的反饋和建議!